package com.rollCall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rollCall.entity.Class;
import com.rollCall.entity.Student;
import com.rollCall.entity.vo.ClassVo;
import com.rollCall.entity.vo.ClazzStudentVo;
import com.rollCall.entity.vo.StudentVo;
import com.rollCall.mapper.ClassMapper;
import com.rollCall.mapper.StudentMapper;
import com.rollCall.entity.result.PageResult;
import com.rollCall.service.ClassService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @date 2025/2/5
 */
@Service
@RequiredArgsConstructor
public class ClassServiceImpl implements ClassService {

	private final ClassMapper classMapper;

	private final StudentMapper studentMapper;

	@Override
	public ClazzStudentVo getClassById(Long id) {
		Class aClass = classMapper.selectById(id);
		if (aClass == null) {
			throw new RuntimeException("班级不存在");
		}
		ClazzStudentVo clazzStudentVo = new ClazzStudentVo();
		clazzStudentVo.setId(aClass.getId());
		clazzStudentVo.setName(aClass.getName());
		clazzStudentVo.setStudentVoList(
				studentMapper.selectList(new QueryWrapper<Student>().eq("class_id", aClass.getId()))
						.stream()
						.map(student -> {
							StudentVo studentVo = new StudentVo();
							studentVo.setId(student.getId());
							studentVo.setName(student.getName());
							studentVo.setUid(student.getUid());
							return studentVo;
						}).collect(Collectors.toList())
		);
		return clazzStudentVo;
	}

	@Override
	public PageResult<ClassVo> getAllClasses(Page<Class> page) {
		page = classMapper.selectPage(page, new QueryWrapper<Class>().orderByAsc("name"));
		List<ClassVo> classVoList = page.getRecords().stream().map(classEntity -> {
			ClassVo classVo = new ClassVo();
			classVo.setId(classEntity.getId());
			classVo.setName(classEntity.getName());
			classVo.setStudentNum(studentMapper.selectCount(new QueryWrapper<Student>().eq("class_id", classEntity.getId())));
			return classVo;
		}).collect(Collectors.toList());
		return new PageResult<>(classVoList.size(), classVoList);
	}

	@Override
	public Class addClass(Class classEntity) {
		if (ObjectUtil.isNotNull(classMapper.selectOne(new QueryWrapper<Class>().eq("name", classEntity.getName())))) {
			throw new RuntimeException("班级已存在");
		}
		if (classEntity.getName() == null || classEntity.getName().isEmpty()) {
			throw new RuntimeException("班级名不能为空");
		}
		classMapper.insert(classEntity);
		return classEntity;
	}

	@Override
	public void deleteClass(Long id) {
		classMapper.deleteById(id);
		studentMapper.delete(new QueryWrapper<Student>().eq("class_id", id));
	}

	@Override
	public List<Class> list() {
		return classMapper.selectList(null);
	}
}
